<template>
	<div class="map-layer-box">
		<div class="mapContent">
			<p>{{showName?'编辑店铺':'新增店铺'}}</p>
			<i class="el-icon-error" @click="close"></i>
			<div class="detail" >
				<el-col :span="24" class="toolbar" style="margin-bottom: 10px;">
					店名*：
					<el-input  
						v-model="storeName" 
						placeholder="店名" 
						maxlength="20"
						style="width:200px; margin-right: 10px;margin-left: 20px;">
					</el-input>
				</el-col>
				<el-col :span="24" class="toolbar" style="margin-bottom: 10px;">
					区域：
					<template>
					  <el-select v-model="proValue" placeholder="请选择" class="i-w--select m-r-10" @change="selectProFn">
						<el-option
						  v-for="item in provinceList"
						  :key="item.id"
						  :label="item.name"
						  :value="item.id">
						</el-option>
					  </el-select>
					</template>
					<template>
						<el-select v-model="cityValue" placeholder="请选择" class="i-w--select" @change="selectCityFn">
							<el-option
							v-for="item in cityList"
							:key="item.id"
							:label="item.name"
							:value="item.id">
							</el-option>
						</el-select>
					</template>
				</el-col>
				<el-col :span="24" class="toolbar" style="margin-bottom: 10px;">
					地址*：
					<!--<el-input 
						v-model="detailAddress" 
						placeholder="地址：城市/区/路" 
						maxlength="50"
						style="width:300px; margin-right: 10px;margin-left: 20px;">
					</el-input>-->
					<el-autocomplete
						class="inline-input"
						v-model="detailAddress"
						:fetch-suggestions="querySearch"
						placeholder="请输入内容"
						:trigger-on-focus="false"
						@select="handleSelect"
					>
					</el-autocomplete>
				</el-col>
				<el-col :span="24" class="toolbar" style="margin-bottom: 10px;">
					顺序号*
					<el-input  
						
						placeholder="序号越大，排列越高。只能输入数字" 
						type="number" 
						v-model="num"
						style="width:300px; margin-right: 10px;margin-left: 20px;">
					</el-input>
				</el-col>
				<!--<el-col :span="24" class="toolbar" style="margin-bottom: 10px;">
					搜索附近：
					<el-input v-model="address" placeholder="请输入地址锁定范围添加坐标" style="width:200px; margin-right: 10px;"></el-input>
					<el-button type="primary" @click="searchKeyword()">搜索</el-button>
				</el-col>-->
				<div class="ma">
					<div id="diyMapcontent"></div>
				</div>
				<el-col :span="24" class="toolbar" style="margin-top: 10px;text-align: center;">
					<el-button type="primary" @click="saveStore()" style="margin: 0 auto;">保存</el-button>
				</el-col>
			</div>
			
		</div>
	</div>
</template>

<script>
	import * as Api from "@/api/Api.js";
	import * as Config from "@/api/Config.js";
	import * as RoundApi from "@/api/RoundApi.js";
	export default {
		props: {
			storeInfo: {
				required: false,
				type: Object,
				default: false
			},
			showName:{
				required: false,
				type: Boolean,
				default: false
			}
		},
		data(){
			return {
				storeName: '', // 店铺名称	
				longitude: '', //经度
				latitude: '', //纬度
				detailAddress: '',
				num:0,
				address: '', // 地址
				geocoder: [], //坐标反查地址实例
				markers: [], //所有标记
				searchService: [], //具名搜索实例
				addForm: {
					longitude: "",
					latitude: ""
				},
				proValue:'',
				cityValue:'',
				cityId: '',
				provinceId: '',
				provinceList: [],
				cityList: [],
				restaurants:[]  // 地址集合
			}
		},
		methods:{
			selectProFn(e){
				console.log(e)
				this.provinceid = e
				this.provinceList.forEach((item, index) => {
					if(item.id == this.provinceid) {
						this.proValue = item.name
					}
				})
				console.log(this.proValue)
				this.cityId = ''
				this.cityValue = ''
				this.getQueryCity()
			},
			selectCityFn(e) {
				this.cityId = e
				this.cityList.forEach((item, index) => {
					if(item.id == this.cityId) {
						this.cityValue = item.name
					}
				})
				console.log(this.cityValue)
			},
			handleSelect(item) {
		        console.log(item);
				this.longitude = item.lng
				this.latitude = item.lat
		      },
			querySearch(queryString, cb) {
				this.restaurants = []
				this.searchKeyword()
				let result = []
		        setTimeout(() => {
					cb(this.restaurants);
				},1000)
		      },
			close() {
				this.$emit('closeStoreBox')
			},
			// 保存店铺
			saveStore() {
				
				if(!this.storeName) {
					this.$message("请填写完整店铺名称");
					return
				}else if(!this.detailAddress) {
					this.$message("请填写完整地址");
					return 
				}else if(!this.num) {
					this.$message("请填写顺序号");
					return
				}else if(!this.addForm.longitude) {
					this.$message("需要选择地理位置才能保持");
					return
				}else if(!this.provinceid) {
					this.$message("请选择省份");
					return
				}else if(!this.cityId) {
					this.$message("请选择城市");
					return
				}
				
				if(!this.storeInfo.address){
					let params = {
						name: this.storeName,
						address: this.detailAddress,
						sort:this.num,
						provinceId: this.provinceid,
						cityId: this.cityId,
						longitude: this.addForm.longitude,
						latitude: this.addForm.latitude
					};
					Api.addStore(this, params).then(res => {
						console.log(res)
						if(res.retCode){
							 this.$message({
					          message: '恭喜你，添加地址成功',
					          type: 'success'
					        });
						}
						this.$emit('closeStore')
					})
				}else{
					let params = {
						id: this.storeInfo.id,
						address: this.detailAddress,
						sort:this.num,
						name: this.storeName,
						longitude: this.addForm.longitude,
						latitude: this.addForm.latitude
					};
					Api.updateStore(this, params).then(res => {
						console.log(res)
						if(res.retCode){
							 this.$message({
					          message: '恭喜你，修改成功',
					          type: 'success'
					        });
						}
						this.$emit('closeStore')
					})
				}
				
				
				
				
				console.log(this.addForm)
			},
			searchKeyword() {
				var keyword = this.detailAddress;

				this.clearOverlays();
				//根据输入的城市设置搜索范围
				 this.searchService.setLocation(`${this.proValue}${this.cityValue}`);
				//根据输入的关键字在搜索范围内检索
				this.searchService.search(keyword);
				//this.geocoder.getLocation(keyword);
			},
			//清除地图上的marker
			clearOverlays() {
				var overlay;
				while((overlay = this.markers.pop())) {
					overlay.setMap(null);
				}
			},
			// 获取省份信息
			getQueryprovince() {
				
				RoundApi.getProvince(this,{}).then(res => {
					console.log(res)
					
					if(res.retCode) {
						this.provinceList = res.data.region
						if(this.provinceid) {
							this.provinceList.forEach((item, index) => {
								if(item.id == this.provinceid) {
									this.proValue = item.name
								}
							})
						}
					}
				});

			},
			getQueryCity() {
				let model = {
					provinceId: this.provinceid
				};
				RoundApi.getQueryCity(this, model).then(res => {
					console.log(res)
					
					if(res.retCode) {
						this.cityList = res.data.region
						console.log(this.cityList)
						if(this.cityId && this.cityList.length>0) {
							this.cityList.forEach((item, index) => {
								if(this.cityId == item.id) {
									this.cityValue =  item.name
								}
							})
						}
					}
				});
			},
			initMap() {
				let self = this;
				console.log(this.latitude, this.longitude);
				var map1 = new qq.maps.Map(document.getElementById("diyMapcontent"), {
					center: new qq.maps.LatLng(this.latitude?this.latitude:39.916527, this.longitude?this.longitude:116.397128),
					zoom: 13
				});
				console.log(map1)
				
				
				self.geocoder = new qq.maps.Geocoder({
					complete: function(result) {
						console.log(result);
						// map1.setCenter(result.detail.location);
						var marker = new qq.maps.Marker({
							position: result.detail.location,
							map: map1
						});
						var info = new qq.maps.InfoWindow({
							map: map1
						});
						//获取标记的点击事件
						info.open();
						info.setContent(
							'<div style="text-align:center;white-space:nowrap;margin:10px;">' +
							result.detail.address +
							"</div>"
						);

						// self.address = result.detail.address;

						info.setPosition(result.detail.location);
						self.markers.push(marker);
						self.markers.push(info);
					}
				});

				var latlngBounds = new qq.maps.LatLngBounds();
				 
				//设置Poi检索服务，用于本地检索、周边检索
				this.searchService = new qq.maps.SearchService({
					
					//检索成功的回调函数
					complete: function(results) {
						//设置回调函数参数
						console.log(results)
						var pois = results.detail.pois;

						if(results.detail.pois) {
							for(var i = 0, l = pois.length; i < l; i++) {
								var poi = pois[i];
								//扩展边界范围，用来包含搜索到的Poi点
								console.log("----", poi.latLng);
								latlngBounds.extend(poi.latLng);
								var marker = new qq.maps.Marker({
									map: map1,
									position: poi.latLng
								});
								let addrseeObj = {
									 value: pois[i].address,
									 name: pois[i].address,
									 lat: pois[i].latLng.lat,
									 lng: pois[i].latLng.lng
								}
								self.restaurants.push(addrseeObj)
								var info = new qq.maps.InfoWindow({
									map: map1
								});
								//获取标记的点击事件
								info.open();
								info.setContent(
									'<div style="text-align:center;white-space:nowrap;margin:10px;">' +
									poi.name +
									"</div>"
								);

								// self.address = poi.name;
								self.addForm.latitude = poi.latLng.lat;
								self.addForm.longitude = poi.latLng.lng;

								info.setPosition(poi.latLng);
								marker.setTitle(i + 1);
								self.markers.push(marker);
								self.markers.push(info);
							}
						} else {
							//  九龙城商务宾馆
							self.address = "";
							self.addForm.longitude = "";
							self.addForm.latitude = "";
						}

						//调整地图视野
						map1.fitBounds(latlngBounds);
					},
					//若服务请求失败，则运行以下函数
					error: function() {
						//self.$message("无法定位该地址");
					}
				});

				qq.maps.event.addListener(map1, "click", function(event) {
					self.addForm.latitude = event.latLng.getLat();
					self.addForm.longitude = event.latLng.getLng();

					self.clearOverlays();
					var marker = new qq.maps.Marker({
						position: new qq.maps.LatLng(
							event.latLng.getLat(),
							event.latLng.getLng()
						),
						map: map1
					});

					var info = new qq.maps.InfoWindow({
						map: map1
					});
					//获取标记的点击事件
					info.open();
					info.setContent(
						'<div style="text-align:center;white-space:nowrap;margin:10px;">' +
						"地址信息" +
						"</div>"
					);

					info.setPosition(event.latLng);
					self.markers.push(marker);
					self.markers.push(info);
				});
			},
		},
		mounted(){
			console.log(this.storeInfo)
			if(this.storeInfo.address) {
				this.storeName = this.storeInfo.name
				this.longitude = this.storeInfo.longitude
				this.latitude = this.storeInfo.latitude
				this.detailAddress = this.storeInfo.address
				this.num = this.storeInfo.sort
				this.addForm.longitude = this.storeInfo.longitude
				this.addForm.latitude = this.storeInfo.latitude
				if(this.storeInfo.provinceId){
					this.cityId = this.storeInfo.cityId
					this.provinceid = this.storeInfo.provinceId
					this.getQueryCity()
				}
			}
			setTimeout(() => {
				this.initMap()
			},500)
			this.getQueryprovince()
		},
	}
</script>

<style>
.i-w--select{
	width: 194px;
	margin-left: 22px;
}
.inline-input{
	width: 400px;
	margin-left: 20px;
}
.map-layer-box{
	position: fixed;
    top: 0px !important;
    right: 0px !important;
    left: 0px !important;
    bottom: 0px !important;
    z-index: 100;
    display: flex;
    flex-direction: column;
    justify-content: center;

    
}
.mapContent{
	width:660px;
	min-height: 660px;
	margin: 0 auto;
	background: #fff;	
	display: flex;
	position: relative;
	flex-direction: column;
	border: 1px solid #E5E5E5;
}
.el-icon-error{
	position: absolute;
	right: 10px;
	top: 10px;
	cursor: pointer;
	color: #666;
	font-size: 20px;
}
p{
	width: 100%;
	height: 30px;
	text-align: center;
}
.detail{
	width: 100%;
	flex: 1;
	padding: 20px;
	flex-direction: column;
}
.ma{
	flex: 1;
}
#diyMapcontent {
		width: 603px;
		height: 0px;
	}
</style>